<template>
  <el-dialog v-model="showDia" :title="props.title + props.username" width="30%" center :show-close="false" :close-on-press-escape="false" :close-on-click-modal="false">
    <el-form
                label-position="top"
                ref="ruleFormRef"
                label-width="100px"
                :rules="rules"
                :model="data"
                style="max-width: 460px; margin-left: 10%;"
                class="login_form"
                scroll-to-error="true"
                size="large"
            >
                <el-form-item class="label" label="头像：" prop="username">
                    <template #default="scope">
                        <el-upload
                        class="avatar-uploader"
                        :action="action"
                        :show-file-list="false"
                        :headers="headders"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                        >
                            <img v-if="imageUrl != '' " :src="imageUrl" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                    </template>
                </el-form-item>
                <el-form-item class="label" label="用户名：" prop="username">
                    <el-input v-model="data.username" />
                </el-form-item>
                <el-form-item label="邮箱：" prop="email">
                    <el-input v-model="data.email"/>
                </el-form-item>
                <el-form-item label="手机号：" prop="phone">
                    <el-input v-model="data.phone"/>
                </el-form-item>
            </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="ok(ruleFormRef)">提交</el-button>
        <el-button type="primary" @click="esc(ruleFormRef)">
          取消
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import {ref,watch, reactive, onMounted} from "vue"
import type { FormInstance, FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {adminLoginOneApi, adminUpdataApi, userLoginOneApi, userUpdataApi} from "../composables/http"
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
const ruleFormRef = ref<FormInstance>()
const headders = ref()
const props = defineProps({
    showDia:{
        type:Boolean,
        default:false
    },
    username:{
        type:String,
        required:true
    },
    title:{
        type:String,
        required:true
    }
})
const validatePhone = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入电话号'))
  } else {
    if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)) {
        callback(new Error('Please 正确的 phone'))
    }
    callback()
  }
}
const rules = reactive<FormRules<typeof data>>({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 11, message: 'Length should be 3 to 8', trigger: 'blur' },
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { min: 5, max: 35, message: 'Length should be 5 to 35', trigger: 'blur' },
    ],
    phone: [{ validator: validatePhone, trigger: 'blur' }],
})
const data = reactive<API.adminLoginOneRes>({
        oldusername:'',
        username:'',
        email: '',
        nickname: '',
        phone: '',
        sign: '',
        avatar: '',
})
const showDia = ref(false)
const action = ref("")
watch(props,()=>{
    showDia.value = props.showDia
    if (props.username.length !=0) {
        // console.log(props.username);
        dataList()
        action.value =`http://127.0.0.1:8000/admin/${props.username}/avatar`
    }
})
const emit = defineEmits(["showDiaf","showusername"]);
const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (response,uploadFile) => {
    if (response.code == 200){
        imageUrl.value = URL.createObjectURL(uploadFile.raw!)
        data.avatar = response.data
    }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  headders.value = {"Authorization" :  localStorage.getItem('d_token')}
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
const dataList = async()=>{
    const d = props.title == "管理员" ? await adminLoginOneApi(props.username) : await userLoginOneApi(props.username)
    data.avatar = d.data.avatar
    if (data.avatar != ""){
        imageUrl.value = data.avatar
    }else{
        imageUrl.value = ""
    }
    data.username = d.data.username
    data.oldusername = d.data.username
    data.email = d.data.email
    data.phone = d.data.phone
}
const ok = (formEl: FormInstance | undefined)=>{
    if (!formEl) return
    formEl.validate(async(valid) => {
    if (valid) {
      const username = (window.localStorage.getItem('d_user')as string)
      const d = props.title == "管理员" ? await adminUpdataApi(username, data) : await userUpdataApi(props.username, data)
      if(d.code == 200){
        emit("showusername","")
        emit("showDiaf",false)
      }
    } else {
      console.log('验证失败!')
      return false
    }
  })
}
const esc = (formEl: FormInstance | undefined)=>{
    emit("showusername","")
    emit("showDiaf",false)
}

</script>


<style lang='scss' scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

:deep .el-form-item__content{
    justify-content: center;
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>